<template>
  <div style="width: 100%; height: 100vh;background-color: darkslateblue;overflow: hidden">
    <div style="width: 400px; margin: 100px auto">
      <div style="color: #cccccc;font-size: 30px;text-align: center;padding: 30px 0">欢迎登录</div>
      <el-form ref="form" :model="user" size="normal" :rules="rules">
        <el-form-item prop="username">
          <el-input :prefix-icon="UserFilled" v-model="user.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input :prefix-icon="Lock" v-model="user.password" show-password></el-input>
        </el-form-item>
        <el-form-item>
          <el-button style="width: 100% " type="primary" @click="login">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import {Lock, UserFilled} from '@element-plus/icons'
import {reactive, ref} from "vue";
import request from "@/util/request";
import {ElMessage} from "element-plus";
import router from "@/router";

export default {
  name: "Login",
  setup() {

    const rules = reactive({
      username: [
        {
          required: true,
          message: '请输入用户名',
          trigger: 'blur',
        }
      ],
      password: [
        {
          required: true,
          message: '请输入密码',
          trigger: 'blur',
        },
      ],
    })
    const loginSucess = () => {
      ElMessage({
        message: "登录成功",
        grouping: true,
        type: 'success'
      })
    }
    const loginFail = () => {
      ElMessage({
        message: "用户名或密码错误",
        grouping: true,
        type: 'error'
      })
    }
    let user = reactive({
      username: '',
      password: ''
    })
    const form = ref(null);
    function login() {
      form.value.validate((valid) => {
        if (valid) {
          request.post("/user/login", user).then(res => {
            if (res.status === 200) {
              loginSucess()
              // 缓存用户信息
              sessionStorage.setItem("user",JSON.stringify(user))
              router.push("/")
            } else {
              loginFail()
            }
          })
        }
      })
    }

    return {user, UserFilled, Lock, login, rules,form}
  }
}
</script>